class_name Player
extends CharacterBody2D

@export var SPEED:float = 16000
@export var accelerattion : float = 2000
@export var rotation_speed: float = 4.0

@onready var turret: Sprite2D = %Turret
@onready var bullet :PackedScene = preload("res://scences/bullet.tscn")

var is_rotating : bool = false
var target_direction: Vector2 = Vector2.RIGHT  # 默认朝右
var friction : float = 0.2
#射击速度 次/秒
var shoot_cool_down :float = 10
var last_shoot_time :float = Time.get_ticks_msec()

var final_rotation:float:
	set(value):
		rotation = value - PI /2
	get:
		return rotation + PI / 2

func _process(delta: float) -> void:
	rotate_turret()
	if Input.is_action_pressed("shoot") and Time.get_ticks_msec() - last_shoot_time > (1000 / shoot_cool_down):
		fire()
		last_shoot_time = Time.get_ticks_msec()

func _physics_process(delta: float) -> void:
	var dir = Input.get_vector("move_left","move_right","move_up","move_down")
	if dir != Vector2.ZERO:
		set_target_direction(dir)
		if is_rotating:
			rotate_to_target(delta)
	
	move_forward(dir,delta)

#region 移动
	
func move_forward(dir:Vector2,delta:float):
	if dir != Vector2.ZERO:
		var add_velocity = Vector2.from_angle(final_rotation) * accelerattion * delta
		velocity += add_velocity
		velocity = velocity.limit_length(SPEED * delta)
	elif velocity.length() > 0:
		velocity *= (1-friction) * delta
	else:
		velocity = Vector2.ZERO
	
	move_and_slide()

func set_target_direction(direction: Vector2):
	target_direction = direction.normalized()
	is_rotating = target_direction.angle() != final_rotation
	
func rotate_to_target(delta:float) -> void:
	var current_angle = final_rotation
	var target_angle = target_direction.angle()
	
	# 计算旋转差值（用最短路径）
	var rotation_delta = rotation_speed * delta
	final_rotation = lerp_angle(current_angle, target_angle, rotation_delta)
	
	#如果角度接近目标，停止旋转
	if abs(current_angle - target_angle) < 0.1:
		final_rotation = target_angle
		is_rotating = false

#endregion

#region 炮台

func rotate_turret() -> void:
	turret.rotation = (get_global_mouse_position() - global_position).angle() - final_rotation 
	
func fire() -> void:
	var bul = bullet.instantiate()
	bul.position = position
	get_tree().root.add_child(bul)
	bul.shoot(global_position.direction_to(get_global_mouse_position()))
#endregion
